import http from './interface'

// let base = 'http://192.168.10.69:15001';
let base = 'https://dyctsapi-dev.guojutech.net';
// let base = 'https://dyctsapi.guojutech.net';
let defaultAppPath = "";
// let defaultAppPath = "/factoring-api";
/* let base = 'http://192.168.0.148:8083';
  let defaultAppPath = ""; */

// if (process.env.NODE_ENV != 'develo0pment') {
    // let env = require('../config/env');
    // base = env.API_URL;
	// base = "https://api-dev.guojutech.net";
 //    defaultAppPath = "/factoring-api";
// }   

const getResponseToken = function(response) {
	let token = response.header["x-auth-token"];

	if (token) {
		return token;
	}
	return response.header["X-auth-Token"];
};

const getStorageToken = function() {
	// uni.showToast({
	// 	title:1111
	// })
	if (globalToken) {
		// console.log("getStorageToken from globalToken: " + globalToken);
		return globalToken;
	}
	// uni.getStorage({
	// 	key:"token",
	// 	success(res){
	// 		return 123
	// 	}
	// })
	// return uni.getStorageSync('x-auth-token');
	return uni.getStorageSync('token');
};

const setStorageToken = function(token) {
	globalToken = token;
	uni.setStorageSync('x-auth-token', token);
};

var globalToken;

const urlEncode = function(param, key, encode) {
    if (param==null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param); 
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
            paramStr += urlEncode(param[i], k, encode)
        }
    }
    return paramStr;
}

const request = function(method, url, data) {
	//设置请求前拦截器
	http.interceptor.request = (config) => {
		const token = getStorageToken();
		if (token) {
			config.header = {
				"X-Auth-Token": token
			}
		}
	}
	//设置请求结束后拦截器
	http.interceptor.response = (response) => {
		console.log(response.data.code);
		console.log(response.data.msg);
		if (!response.header) {
			uni.showToast({
				title: "网络错误",
				duration:3000,
				icon: 'none'
			});
			return;
		}

		if ( (response.data.code == 500 && response.data.msg == 'UNAUTHORIZED') ||  response.data.msg.indexOf("UNAUTHORIZED") != -1) {
			
			// 重新登录
			uni.showModal({
			    title: '提示',
			    content: '登录已过期，重新登录',
			    success: function (res) {
			        if (res.confirm) {
			           uni.reLaunch({
			           	url: '/pages/auth/index'
			           });
			        } else if (res.cancel) {
			            console.log('用户点击取消');
			        }
			    }
			});
			
			return;
		}
		
		const token = getStorageToken();
		const rspToken = getResponseToken(response);
		// console.log("token: " + token + ", rspToken: " + rspToken);
		if (rspToken && rspToken != token) {
			setStorageToken(rspToken);
		}
		
		return response;
	}
	return http.request({
		baseUrl: `${base}`,
		dataType: 'json',
		url,
		method,
	    data,
	})
};

const buildUrl = function (urlPath, appPath) {
    if (!urlPath) {
        urlPath = "";
    }
    if (urlPath && urlPath.length > 0 && !urlPath.startsWith("/")) {
        urlPath = "/" + urlPath;
    }
    if (!appPath) {
        appPath = defaultAppPath;
    }
	if (appPath && appPath.length > 0 && !appPath.startsWith("/")) {
	    appPath = "/" + appPath;
	}
    return appPath + urlPath;
};

const postApi = function (url, appPath) {
    return params => {
		let paraUrl = urlEncode(params || {});
		let fetchUrl = paraUrl ? url + "?" + paraUrl.slice(1) : url;
		
        return request("POST", buildUrl(fetchUrl, appPath))
            .then(res => res.data);
    }
};

const postJsonApi = function (url, appPath) {
    return json => {
        let data = json ? json : null;
        return request("POST", buildUrl(url, appPath), data)
            .then(res => res.data);
    }
};

const getApi = function (url, appPath) {
    return params => {
		let paraUrl = urlEncode(params || {});
		let fetchUrl = paraUrl ? url + "?" + paraUrl.slice(1) : url;
		
        return request("GET", buildUrl(fetchUrl, appPath))
            .then(res => res.data);
    };
};

const buildFetchUrl = function(path) {
	return base + buildUrl(path, defaultAppPath);
};

export default {
    buildUrl,
	buildFetchUrl,
	baseUrl: base,
    postApi,
    postJsonApi,
    getApi
}